#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#define lowbit(x) (x & (-x))

const int N = 100005;
int m, n, cur, tot, cnt, pcnt;
int fa[N], tr[26][N], fail[N], val[N], ans[N], siz[N], dfn[N], pos[N], len[N];
int e_cnt, heads[N];
char str[N];

struct Edge {
  int v, nxt;
} e[N];

struct Query {
  int pos;
  int id;
};

std::vector<Query> qs[N];

inline int query(int x) {
  int res = 0;
  while (x) {
    res += val[x];
    x -= lowbit(x);
  }
  return res;
}

inline void modify(int x, int v) {
  while (x <= cnt) {
    val[x] += v;
    x += lowbit(x);
  }
}

inline void add(int u, int v) { e[++e_cnt].v = v, e[e_cnt].nxt = heads[u], heads[u] = e_cnt; }

inline void insert(char ch) {
  if (!tr[ch - 'a'][cur])
    tr[ch - 'a'][cur] = ++tot, fa[tr[ch - 'a'][cur]] = cur, len[tot] = len[cur] + 1;
  cur = tr[ch - 'a'][cur];
}

void getfail() {
  std::queue<int> q;
  for (int i = 0; i < 26; ++i) {
    if (tr[i][0]) {
      fail[tr[i][0]] = 0;
      q.push(tr[i][0]);
    }
  }
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    for (int i = 0, v; i < 26; ++i) {
      if ((v = tr[i][u])) {
        fail[v] = tr[i][fail[u]];
        q.push(v);
      } else {
        tr[i][u] = tr[i][fail[u]];
      }
    }
  }
  for (int i = 1; i <= tot; ++i) {
    add(fail[i], i);
  }
}

void dfs1(int x) {
  siz[x] = 1, dfn[x] = ++cnt;
  for (int i = heads[x]; i; i = e[i].nxt) {
    int v = e[i].v;
    dfs1(v);
    siz[x] += siz[v];
  }
}

void dfs2(int x) {
  modify(dfn[x], 1);
  for (std::vector<Query>::iterator i = qs[x].begin(); i != qs[x].end(); ++i) {
    ans[i->id] = query(dfn[i->pos] + siz[i->pos] - 1) - query(dfn[i->pos] - 1);
  }
  for (int i = 0; i < 26; ++i)
    if (len[tr[i][x]] > len[x]) {
      dfs2(tr[i][x]);
    }
  modify(dfn[x], -1);
}

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("testdata.in", "r", stdin);
  freopen("testdata.out", "w", stdout);
#endif
#ifndef LOCAL
  freopen("P2414[NOI2011]Typer.in", "r", stdin);
  freopen("P2414[NOI2011]Typer.out", "w", stdout);
#endif
#endif

  scanf("%s", str + 1);
  for (int i = 1; str[i]; ++i) {
    if (str[i] == 'B') {
      cur = fa[cur];
    } else if (str[i] == 'P') {
      pos[++pcnt] = cur;
    } else
      insert(str[i]);
  }
  getfail();
  int u, v;
  dfs1(0);
  scanf("%d", &m);
  for (int i = 1; i <= m; ++i) {
    scanf("%d%d", &u, &v);
    qs[pos[v]].push_back((Query){pos[u], i});
  }
  dfs2(0);
  for (int i = 1; i <= m; ++i) {
    printf("%d\n", ans[i]);
  }
  return 0;
}